<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Client\Contract\ClientContract;

/**
 * 公海列表.
 *
 * Class IndexLogic
 */
class PublicIndexLogic
{
    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;


    /**
     * 成员列表.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        //返回的数据格式
        $data = [
            'page' => [
                'page' => $params['page'],
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];
        $where = [];
        $where[] = ['b2b_manager_name', '=', null];
        $option = ['orderByRaw' => 'id asc', 'perPage' => $params['perPage'], 'page' => $params['page'], 'pageName' => 'page'];
        if ($params['mobile']) {
            $where[] = ['mobile', '=', $params['mobile']];
        }
        $where[] = ['is_failure', '=', $params['is_failure']];
        if ($params['b2bClientKeyword']) {
            $where[] = ['b2b_client_name', 'LIKE', '%' . $params['b2bClientKeyword'] . '%'];
        }
        if ($params['enterpriseKeyword']) {
            $where[] = ['enterprise_name', 'LIKE', '%' . $params['enterpriseKeyword'] . '%'];
        }
        if ($params['b2bSalesmanName']) {
            $where[] = ['b2b_salesman_name', 'LIKE', '%' . $params['b2bSalesmanName'] . '%'];
        }
        if ($params['b2bManagerName']) {
            $where[] = ['b2b_manager_name', 'LIKE', '%' . $params['b2bManagerName'] . '%'];
        }
        $res = $this->clientService->getClientList($where, ['*'], $option);
        if (empty($res['data'])) {
            return $data;
        }
        foreach ($res['data'] as &$value) {
            $province=Db::table('district')->where('id',$value['province'])->value('name');
            $city=Db::table('district')->where('id',$value['city'])->value('name');
            $district=Db::table('district')->where('id',$value['district'])->value('name');
            $value['preAddress'] = $province.$city.$district;
        }
        $data['list'] = $res['data'];
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        return $data;
    }

}
